package renguanyu.app.auth4fx.controller.permission;

import javafx.concurrent.Task;
import renguanyu.app.auth4fx.App;
import renguanyu.app.auth4fx.model.permission.PermissionDto;
import renguanyu.app.auth4fx.service.permission.PermissionService;
import renguanyu.app.auth4fx.view.permission.PermissionInfoUpdateView;
import renguanyu.app.auth4fx.view.permission.PermissionListView;

public class PermissionInfoUpdateController extends Task<Void> {

    PermissionInfoUpdateView permissionInfoUpdateView;
    public PermissionInfoUpdateController(PermissionInfoUpdateView permissionInfoUpdateView) {
        this.permissionInfoUpdateView = permissionInfoUpdateView;
    }

    public void execute() {
        System.out.println("PermissionInfoUpdate.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private Integer affectedRows = 0;
    @Override
    protected Void call() {
        System.out.println("PermissionInfoUpdate.call");
        PermissionDto permissionDto = buildPermissionDto();
        affectedRows = PermissionService.updatePermission(permissionDto);
        return null;
    }

    private PermissionDto buildPermissionDto() {
        String id = permissionInfoUpdateView.selectedPermission.getId();
        String name = permissionInfoUpdateView.nameProperty.get();
        PermissionDto permissionDto = new PermissionDto();
        permissionDto.setId(id);
        permissionDto.setName(name);
        return permissionDto;
    }

    @Override
    protected void running() {
        System.out.println("PermissionInfoUpdate.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("PermissionInfoUpdate.succeeded");
        if(affectedRows == 1){
            App.mainView.setCenter(new PermissionListView());
        }
    }

    @Override
    protected void failed() {
        System.out.println("PermissionInfoUpdate.failed");
    }
}
